layui.define(function(exports){ //提示：模块也可以依赖其它模块，如：layui.define('layer', callback);
  var sysRolePage = {
    render: function(){
    	var $ = layui.$,
    	table = layui.table,
    	layer = layui.layer,
    	tree = layui.tree,
    	form = layui.form,
    	util = layui.util,
    	laydate = layui.laydate;
    	var optName;
    	var treeObject;
    	loadTree();
    	setFullHeight('treePanel');
    	var tableObj = table.render({
    	  id: 'main-table',
    	  elem: '#table', //指定原始表格元素选择器（推荐id选择器）
    	  url: '/boss/sys_role/query_list',
    	  method:'post',
    	  autoSort : false,
		  even: false,
    	  toolbar: '#toolbar',
    	  height: 'full-70',
    	  limits : [10,30,50,100],
    	  limit: 30,
    	  page: true,
    	  cols: [[
    		  {type:'radio'},
    		  {field: 'roleName', title: '角色名称',sort:false,templet: function(d){
    			  switch(d.roleName) {
    			  	case null:
    			  		return '空';
    			  	case '':
    			  		return '--';
    			  	default:
    			  		return d.roleName;
    			  }
    	      }},
    		  {field: 'roleCode', title: '角色编码',sort:false,templet: function(d){
    			  switch(d.roleCode) {
    			  	case null:
    			  		return '空';
    			  	case '':
    			  		return '--';
    			  	default:
    			  		return d.roleCode;
    			  }
    	      }},
    		  {fixed: 'right', title:'操作', toolbar: '#optbar', width:165}
    	  ]],
    	  done: function(res, curr, count){
		  }
    	});
    	
    	function loadTree(){
  		  $.post(
  			'/boss/sys_resource/tree_data_source',
  		    null,
  		    function(data, textStatus, jqXHR){
  				treeObject = tree.render({
  		    	    elem : '#treePanel',
  		    	    data : data,
  		    	    showCheckbox : true,
  		    	    accordion : false,
  		    	    onlyIconControl : true,
  		    	    text : {
	    	    	  defaultNodeName: '[新建节点]' //节点默认名称
	    	    	  ,none: '无数据' //数据为空时的提示文本
	    	    	}
  		    	  });
  		    },"json");
  	    }
    	
    	$('#treePanel').on('click','.layui-icon-subtraction',function(){
  			$.post(
    			'/boss/sys_resource/update_item',
    		    {
    				id:$(this).parent().next('input').val(),
    				name:$(this).parent().nextAll('.layui-tree-txt').text(),
    				spread:true
    			},
    		    null,"json");
		  })
		  $('#treePanel').on('click','.layui-icon-addition',function(){
			  $.post(
    			'/boss/sys_resource/update_item',
    		    {
    				id:$(this).parent().next('input').val(),
    				name:$(this).parent().nextAll('.layui-tree-txt').text(),
    				spread:false
    			},null,"json");
		  })
    	
    	function setFullHeight(id){
			var setEleH = function(){
				var w_h = window.innerHeight
				var e_h = w_h - 60 - 20 - 73
				document.getElementById(id).style.height = e_h+'px'
				document.getElementById(id).style.overflowY = 'auto'
			}
			window.onresize = function(){  
			  setEleH();
			}
			setEleH();
		}
    	var selectedRow;
    	table.on('row(table)', function(obj){
    	    var data = obj.data;
    	    $.post(
    	    	    "/boss/sys_role/getResourceByRoleId",
    	    	    {roleId:data.id},
    	    	    function(data2, textStatus, jqXHR){
    	    	    	treeObject.reload();
    	    	    	treeObject.setChecked(data2);
    	    	    },"json");
    	    selectedRow = obj.data;
    	    console.log(selectedRow)
			$(obj.tr).find('.laytable-cell-radio input[type=radio]').prop('checked','true');
			$('.laytable-cell-radio .layui-icon').html('').removeClass('layui-icon-radio').addClass('layui-icon-circle')
			$('.laytable-cell-radio .layui-form-radio').removeClass('layui-form-radioed')
			$(obj.tr).find('.laytable-cell-radio .layui-icon').html('').removeClass('layui-icon-circle').addClass('layui-icon-radio')
			$(obj.tr).find('.laytable-cell-radio .layui-form-radio').addClass('layui-form-radioed')
			$(obj.tr).parent().find("tr").removeClass('layui-table-click')
			$(obj.tr).addClass('layui-table-click')
    	    
    	  });

    	
    	/** 顶部toolbar事件 **/
    	table.on('toolbar(table)', function(obj){
    		switch(obj.event){
    		  case 'refresh-opt':
  			    tableObj.reload();
  			  break;
    		  case 'addData-opt':
    			  var data = obj.data;
    			  optName = 'new';
    			  layer.open({
    				  type: 1,
    				  area: ['700px','200px'],
    				  title : '新增/添加',
    				  content: $('#windows'),
    				  resize : false,
    				  move : false,
    				  shadeClose : false,
    				  btn : [ '确定', '取消' ],
    				  success : function(layero, index){
    					  $('#win-form')[0].reset();
    				  },
					  yes : function(index, layero) {
						  $('#win-submit').trigger('click');
					  }
    				});
		      break;
    		  case 'batch-del-opt':
    			  var checkStatus = table.checkStatus('main-table');
    			  if(checkStatus.data.length ==0){
    				  layer.alert('请先选择待删除行',{icon: 5});
    				  return;
    			  }
    			  layer.confirm("你确定批量删除"+checkStatus.data.length+"个项目吗？", {icon: 3, title:'提示'},
			            function(index){//确定回调
    				  		var keys = new Array();
    				  		$.each(checkStatus.data,function(i,item){
    				  			keys.push(item.id);
    				  		});
    				  		batchDelete(keys,index);
			            },function (index) {//取消回调
			               layer.close(index);
			            }
			        );
    			  break;
    		  case 'save_role_resource_opt':
    			  
//    			  var checkStatus = table.checkStatus('main-table');
    			  var checkStatus = selectedRow;
    			  if(checkStatus == undefined || checkStatus == null){
    				  layer.alert('请先选择待设置角色',{icon: 5});
    				  return;
    			  }
    			  var roleid = checkStatus.id;
    			  
    			  var checkedData = treeObject.getChecked();
    			  var keys = new Array();
    		      getSelected(roleid,keys,checkedData);
    			  console.log(keys);
    			  
    			  $.ajax({
    				    type: 'POST',
    				    url: '/boss/sys_role/updateRoleResource',
    				    data: JSON.stringify(keys),
    				    success: function (data) {
    				        if(data.success){
    				    	    layer.msg(data.message);
    				        }else{
    				            layer.msg(data.message,{icon: 5,anim: 6,time: 0,btn:['确定']});
    				        }
    				    },
    				    error: function(data) {
    				        layer.msg(data.responseText,{icon: 5,anim: 6,time: 0,btn:['确定']});
    				    },
    				    dataType: "json",
    				    contentType: "application/json"
    				});
    			  
    			  break;
    		}
    	});
    	
    	function getSelected(roleid,keys,checkedData){
    		$.each(checkedData,function(i,item){
	  			if(item.children.length > 0){
	  				getSelected(roleid,keys,item.children);
	  			} else {
	  				keys.push({roleId:roleid,resourceId:item.id});
	  			}
	  		});
    	}
    	
    	form.on('submit(win-submit)', function(data){
  		  $.ajax({
  			    type: 'POST',
  			    url: optName=='new'?'/boss/sys_role/add_item':'/boss/sys_role/update_item',
  			    data: data.field,
  			    success: function (data) {
  			        if(data.success){
  			        	layer.closeAll();
  			        	tableObj.reload();
  			        	layer.msg(data.message);
  			        }else{
  			            layer.msg(data.message,{icon: 5,anim: 6,time: 0,btn:['确定']});
  			        }
  			    },
  			    error: function(data) {
  			        layer.msg(data.responseJSON.message,{icon: 5,anim: 6,time: 0,btn:['确定']});
  			    },
  			    dataType: "json"
  			});
  		  return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
  		});
    	
    	util.event('opt_user', {
    		refresh_opt: function(othis){
    			loadTree();
		    }
		});
    	
    	/** 右侧tool事件 **/
    	table.on('tool(table)', function(obj){
    		var data = obj.data;
    		switch(obj.event){
    		  case 'edit-opt':
    			  optName = 'update';
    			  layer.open({
    				  type: 1,
    				  area: ['700px','200px'],
    				  title : '编辑',
    				  content: $('#windows'),
    				  shadeClose : false,
    				  move : false,
    				  btn : [ '确定', '取消' ],
    				  success : function(layero, index){
    					  $('#win-form')[0].reset();
    					  $.post(
    							  "/boss/sys_role/get_by_pk",
    							  {id:data.id},
    							  function(data, textStatus, jqXHR){
    								  form.val("win-form",data);
    							  },"json");
    				  },
					  yes : function(index, layero) {
						  $('#win-submit').trigger('click');
					  }
    				});
    			  break;
    		  case 'del-opt':
    			  layer.confirm("你确定删除项目“"+obj.data.roleName+"”吗？", {icon: 3, title:'提示'},
  			            function(index){//确定回调
      				  		var keys = new Array();
      				  		keys.push(obj.data.id);
      				  		batchDelete(keys,index);
  			            },function (index) {//取消回调
  			               layer.close(index);
  			            }
  			        );
    			  break;
    		}
    	});
    	
    	form.on('submit(search-opt)',function(data){
    		tableObj.reload({where:data.field});
    	    return false;
    	});
    	
    	$('#search-more').click(function(){
    		layer.open({
				  type: 1,
				  area: ['1024px','468px'],
				  title : '更多查询条件',
				  content: $('#windows-search'),
				  resize : true,
				  shadeClose : true,
				  shade : false,
				  btn : [ '查询', '关闭' ],
				  success : function(layero, index){
				  },
				  yes : function(index, layero) {
					tableObj.reload({where:form.val('win-search-form')});
				  }
				});
    	});
    	
    	function batchDelete(keys,index){
    		$.ajax({
	                type: 'POST',
	                url: '/boss/sys_role/delete_item',
	                data: JSON.stringify(keys),
	                success: function (data) {
	                    if(data.success){
	                        layer.close(index);
	                    }else{
	                        layer.msg(data.message,{icon: 5,anim: 6,time: 0,btn:['确定']});
	                    }
	                    tableObj.reload();
	                    layer.msg(data.message);
	                },
	                error: function(data) {
	                    layer.msg(data.responseText,{icon: 5,anim: 6,title:'错误',time: 0,btn:['确定']});
	                },
	                contentType: "application/json",
	                dataType: "json"
	            });
    	}
    	
    	laydate.render({
		    elem: '#createTimeStrStart',
		    type: 'datetime'
		  });
    	laydate.render({
		    elem: '#createTimeStrEnd',
		    type: 'datetime'
		  });
    	laydate.render({
		    elem: '#createTimeStrStart-win',
		    type: 'datetime'
		  });
    	laydate.render({
		    elem: '#createTimeStrEnd-win',
		    type: 'datetime'
		  });
    	laydate.render({
		    elem: '#createTime-win',
		    type: 'datetime'
		  });
    	laydate.render({
		    elem: '#updateTimeStrStart',
		    type: 'datetime'
		  });
    	laydate.render({
		    elem: '#updateTimeStrEnd',
		    type: 'datetime'
		  });
    	laydate.render({
		    elem: '#updateTimeStrStart-win',
		    type: 'datetime'
		  });
    	laydate.render({
		    elem: '#updateTimeStrEnd-win',
		    type: 'datetime'
		  });
    	laydate.render({
		    elem: '#updateTime-win',
		    type: 'datetime'
		  });
    	
    }
  };
  
  //输出test接口
  exports('sysRolePage', sysRolePage);
});